<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Validate;
use app\common\library\Token;
/**
 * 会员接口
 */
class User extends Api
{

    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     * 
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password)
        {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret)
        {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     * 
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha)
        {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$"))
        {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin'))
        {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user)
        {
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        }
        else
        {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret)
        {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     * 
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     */
    public function register()
    {
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        // $username = $this->request->request('username');
        $password = $this->request->request('password');
        $repassword = $this->request->request('repassword');
        // $email = $this->request->request('email');
        
        if (!$mobile && !Validate::regex($mobile, "^1\d{10}$"))
        {
            $this->error(__('Mobile is incorrect'));
        }
        if ($code!=666) {
            $this->error('验证码不正确');
        }
        if (!$password) {
            $this->error('请输入密码');
        }
        if ($password!=$repassword) {
            $this->error('两次密码不一致');
        }
        // if (!$username || !$password)
        // {
        //     $this->error(__('Invalid parameters'));
        // }
        // if ($email && !Validate::is($email, "email"))
        // {
        //     $this->error(__('Email is incorrect'));
        // }
        $ret = $this->auth->register('', $password, '', $mobile, []);
        if ($ret)
        {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     * 
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar');
        $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
        if ($exists)
        {
            $this->error(__('Username already exists'));
        }
        $user->username = $username;
        $user->nickname = $nickname;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     * 
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha)
        {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email"))
        {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find())
        {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result)
        {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     * 
     * @param string $email 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {   
        $token = $this->request->request('token');
        //根据token获取用户信息
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        }

        $oldmobile = $this->request->request('oldmobile');
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        $phone = Db('user')->where(['id'=>$userid['user_id']])->value('mobile');
        if ($oldmobile != $phone)
        {
            $this->error("原手机账号不正确");
        }
        if (!$mobile || !$code)
        {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$"))
        {
            $this->error(__('Mobile is incorrect'));
        }
        $res = Db('user')->where(['mobile'=>$mobile])->find();
        if ($res)
        {
            $this->error("手机号已存在");
        }
        // $result = Sms::check($mobile, $captcha, 'changemobile');
        if ($code != 666)
        {
            $this->error(__('Captcha is incorrect'));
        }

        //执行修改
        $r = Db('user')->where(['id'=>$userid['user_id']])->update(['mobile'=>$mobile]);
        if ($r) {
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
        
    }

    /**
     * 第三方登录
     * 
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform]))
        {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result)
        {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret)
            {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     * 
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        // $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        // $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $renewpassword = $this->request->request("renewpassword");
        // $captcha = $this->request->request("captcha");
        // if (!$newpassword || !$captcha)
        // {
        //     $this->error(__('Invalid parameters'));
        // }

        
            if (!$mobile || !Validate::regex($mobile, "^1\d{10}$"))
            {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user)
            {
                $this->error("该手机用户不存在");
            }
            // $ret = Sms::check($mobile, $captcha, 'resetpwd');
            // if (!$ret)
            // {
            //     $this->error(__('Captcha is incorrect'));
            // }
            // Sms::flush($mobile, 'resetpwd');
            $code = $this->request->request('code');
            if ($code!=666) {
                $this->error("验证码错误");
            }
        if ($newpassword != $renewpassword) {
            $this->error("两次密码不一致");
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret)
        {
            $this->success(__('Reset password successful'));
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }

   

    /**
     * 获取个人信息
     * 
     * 
     */
    public function getuserinfo(){
        $token = $this->request->request('token');
        //根据token获取用户信息
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        }
        $userinfo = Db('user')->field('id,nickname,mobile,avatar')->where(['id'=>$userid['user_id']])->find();
        if ($userinfo) {
            $this->success('操作成功',$userinfo);
        }else{
            $this->error('获取失败');
        }
    }
    /**
     * 修改头像
     * 
     */
    public function avatar(){
        $token = $this->request->request('token');
        $avatar = $this->request->request('avatar');
        //根据token获取用户信息
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        }
        $r = Db('user')->where(['id'=>$userid['user_id']])->update(['avatar'=>$avatar]);
        if ($r) {
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }
    /**
     * 修改昵称
     * 
     */
    public function nickname(){
        $token = $this->request->request('token');
        $nickname = $this->request->request('nickname');
        //根据token获取用户信息
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        }
        $r = Db('user')->where(['id'=>$userid['user_id']])->update(['nickname'=>$nickname]);
        if ($r) {
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }



    /**
     * 我的课程列表
     * 
     */
    public function mycurriculum()
    {   
        $token = $this->request->request('token');
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        }
        $where['user_id'] = $userid['user_id'];
        //获取我报名的课程id
        $list = Db('sign_up')->field('curriculum_id')->where($where)->select();
        if (!$list) {
            $this->error('无报名课程');
        }
        foreach ($list as $key => $value) {
            //获取我报名的课程
            $curr[$key] = Db('curriculum')->where(['id'=>$value['curriculum_id']])->find();
        }
        foreach ($curr as $key => $value) {
            $curr[$key]['images'] = explode(',',$value['images']);
            $curr[$key]['images'] = array_slice($curr[$key]['images'],1);
        }
        if ($curr) {
            $this->success('操作成功',$curr);
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 留言
     * 
     */
    public function message(){ 
        $token = $this->request->request('token');
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        }
        $content = $this->request->request('content');
        if (!$content) {
            $this->error('内容不能为空');
        }
        $data['user_id'] = $userid['user_id'];
        $data['content'] = $content;
        $r = Db('message')->insert($data);
        if ($r) {
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
}
